#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include "myfont.h"
#include "smart_home_ui.h"  // 添加智能家居界面头文件
#include "boot_screen.h"    // 添加开机界面头文件
#include "shutdown_screen.h"  // 添加关机界面头文件
#include "device_state_manager.h"  // 添加设备状态管理头文件
#include "light_control.h"  // 添加灯光控制头文件
#include "led_control.h"    // 添加LED控制头文件
#include "smoke_monitor.h"  // 添加烟雾监控头文件
#include "call_screen.h"    // 添加呼叫页面头文件

// 函数原型声明
uint32_t custom_tick_get(void);
void boot_complete_handler(void);
void mqtt_init_timer_cb(lv_timer_t *timer);
void restore_state_timer_cb(lv_timer_t *timer);
void smoke_monitor_timer_cb(lv_timer_t *timer);

// 进一步增加显示缓冲区大小，确保足够的缓冲空间
#define DISP_BUF_SIZE (512 * 1024)

/**
 * @brief 强制清除屏幕残影的函数
 * @note 通过多次刷新和清屏操作彻底消除显示残影
 */
void force_clear_screen_ghosting(void) {
    lv_disp_t *disp = lv_disp_get_default();
    if(disp) {
        // 多次强制刷新以确保清除残影
        for(int i = 0; i < 3; i++) {
            lv_obj_invalidate(lv_scr_act());
            lv_refr_now(disp);
            // 短暂延迟让硬件完成刷新
            usleep(5000);
        }
        
        // 设置黑色背景并强制刷新
        lv_disp_set_bg_color(disp, lv_color_hex(0x000000));
        lv_disp_set_bg_opa(disp, LV_OPA_COVER);
        lv_obj_invalidate(lv_scr_act());
        lv_refr_now(disp);
    }
}

int main(void)
{
    /*LittlevGL init*/
    lv_init();
    
    // 初始化设备状态管理器
    device_state_manager_init();
    
    // 初始化烟雾监控系统
    if (smoke_monitor_init() != 0) {
        printf("警告: 烟雾监控系统初始化失败\n");
    }
    
    /*Linux frame buffer device init*/
    fbdev_init();

    /*使用双缓冲区来减少拖影和闪烁*/
    static lv_color_t buf1[DISP_BUF_SIZE];
    static lv_color_t buf2[DISP_BUF_SIZE];

    /*Initialize a descriptor for the buffer*/
    static lv_disp_draw_buf_t disp_buf;
    lv_disp_draw_buf_init(&disp_buf, buf1, buf2, DISP_BUF_SIZE);

    /*Initialize and register a display driver*/
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.draw_buf   = &disp_buf;
    disp_drv.flush_cb   = fbdev_flush;
    disp_drv.hor_res    = 1024;
    disp_drv.ver_res    = 600;
    
    // 优化显示设置以减少拖影
    disp_drv.full_refresh = 1;      // 启用整屏刷新，确保完整重绘
    disp_drv.direct_mode = 0;       // 禁用直接模式，使用缓冲区
    disp_drv.antialiasing = 1;      // 启用抗锯齿
    disp_drv.screen_transp = 0;     // 禁用屏幕透明度
    disp_drv.sw_rotate = 0;         // 禁用软件旋转
    disp_drv.rotated = 0;           // 禁用旋转
    
    lv_disp_drv_register(&disp_drv);

    // 设置显示器的全局背景色与不透明度（黑色作为防残影底色）
    lv_disp_t *disp = lv_disp_get_default();
    if(disp) {
        lv_disp_set_bg_color(disp, lv_color_hex(0x000000));
        lv_disp_set_bg_opa(disp, LV_OPA_COVER);
    }

    evdev_init();
    static lv_indev_drv_t indev_drv_1;
    lv_indev_drv_init(&indev_drv_1); /*Basic initialization*/
    indev_drv_1.type = LV_INDEV_TYPE_POINTER;

    /*This function will be called periodically (by the library) to get the mouse position and state*/
    indev_drv_1.read_cb = evdev_read;
    lv_indev_t *mouse_indev = lv_indev_drv_register(&indev_drv_1);

    /*Set a cursor for the mouse*/
    LV_IMG_DECLARE(mouse_cursor_icon)
    lv_obj_t * cursor_obj = lv_img_create(lv_scr_act()); /*Create an image object for the cursor */
    lv_img_set_src(cursor_obj, &mouse_cursor_icon);           /*Set the image source*/
    lv_indev_set_cursor(mouse_indev, cursor_obj);             /*Connect the image  object to the driver*/

    // 设置鼠标设备到关机界面模块，以便关机时隐藏光标
    set_mouse_indev(mouse_indev);

    // 设置开机完成回调并创建开机界面
    set_boot_complete_callback(boot_complete_handler);
    create_boot_screen();
    
    /*Handle LitlevGL tasks with optimized timing to reduce ghosting*/
    while(1) {
        lv_timer_handler();
        // 进一步减少延迟以提高刷新率，彻底消除拖影
        usleep(8000);  // 8ms延迟，约125Hz刷新率
        
        // 定期强制刷新以防止累积残影
        static int refresh_counter = 0;
        if(++refresh_counter >= 50) {  // 每400ms强制刷新一次
            lv_obj_invalidate(lv_scr_act());
            refresh_counter = 0;
        }
    }

    return 0;
}

/*Set in lv_conf.h as `LV_TICK_CUSTOM_SYS_TIME_EXPR`*/
uint32_t custom_tick_get(void)
{
    static uint64_t start_ms = 0;
    if(start_ms == 0) {
        struct timeval tv_start;
        gettimeofday(&tv_start, NULL);
        start_ms = (tv_start.tv_sec * 1000000 + tv_start.tv_usec) / 1000;
     }

    struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    uint64_t now_ms;
    now_ms = (tv_now.tv_sec * 1000000 + tv_now.tv_usec) / 1000;

    uint32_t time_ms = now_ms - start_ms;
    return time_ms;
}

// MQTT初始化定时器回调函数
void mqtt_init_timer_cb(lv_timer_t *timer) {
    lv_timer_del(timer);
    init_mqtt_cloud_integration();
}

// 状态恢复定时器回调函数
void restore_state_timer_cb(lv_timer_t *timer) {
    lv_timer_del(timer);
    
    // 首先恢复用户设置（包括四个灯的状态和空调电源状态）
    load_user_settings();
    
    // 然后恢复其他设备状态（温度、模式等，但不包括空调电源状态）
    if(restore_device_states()) {
        // 设备状态恢复完成
    } else {
        // 未找到保存的状态文件，使用默认设置
    }
    
    // 确保空调电源状态正确同步到界面
    printf("DEBUG: 最终空调电源状态: %s\n", global_ac_power_state ? "开启" : "关闭");
    
    // 应用恢复的灯光状态到硬件LED
    led_set_state(LED1_GPIO, global_light1_state);  // 客厅灯
    led_set_state(LED2_GPIO, global_light2_state);  // 卧室灯
    led_set_state(LED3_GPIO, global_light3_state);   // 厨房灯  
    led_set_state(LED4_GPIO, global_light4_state);   // 阳台灯
    
    // 同步更新灯光控制界面的UI状态（如果界面已创建）
    set_light_state(0, global_light1_state);  // 客厅灯
    set_light_state(1, global_light2_state);  // 卧室灯
    set_light_state(2, global_light3_state);   // 厨房灯
    set_light_state(3, global_light4_state);   // 阳台灯
    
    // 直接设置全局LED状态数组，确保界面创建时使用正确的状态
    set_global_led_state(0, global_light1_state);  // 客厅灯
    set_global_led_state(1, global_light2_state);  // 卧室灯
    set_global_led_state(2, global_light3_state);   // 厨房灯
    set_global_led_state(3, global_light4_state);   // 阳台灯
    
    // 调试输出：显示设置后的状态
    printf("DEBUG: 开机后设置全局LED状态 - 灯1:%s, 灯2:%s, 灯3:%s, 灯4:%s\n",
           global_light1_state ? "开" : "关",
           global_light2_state ? "开" : "关",
           global_light3_state ? "开" : "关",
           global_light4_state ? "开" : "关");
    
    // 再延迟1秒后初始化MQTT云平台集成
    lv_timer_t *mqtt_init_timer = lv_timer_create(mqtt_init_timer_cb, 1000, NULL);
    lv_timer_set_repeat_count(mqtt_init_timer, 1);
    
    // 启动烟雾监控定时器（每秒检查一次）
    lv_timer_create(smoke_monitor_timer_cb, 1000, NULL);
    printf("烟雾监控定时器已启动，每秒检查一次烟雾浓度\n");
}

// 烟雾监控定时器回调函数
void smoke_monitor_timer_cb(lv_timer_t *timer) {
    // 执行烟雾监控任务
    smoke_monitor_task();
    
    // 获取当前烟雾数据并输出调试信息
    static uint32_t debug_counter = 0;
    if (++debug_counter >= 10) { // 每10秒输出一次调试信息
        smoke_sensor_data_t data = get_smoke_sensor_data();
        printf("烟雾监控: 当前浓度=%u, 警报状态=%s, 蜂鸣器=%s\n", 
               data.smoke_concentration,
               data.alarm_active ? "激活" : "正常",
               data.buzzer_enabled ? "启用" : "禁用");
        debug_counter = 0;
    }
}

// 开机完成处理函数
void boot_complete_handler(void) {
    printf("开机界面完成，启动智能家居系统...\n");
    
    // 配置华为云平台参数
    set_cloud_config(
        "https://your-api-gateway-url.cn-north-1.myhuaweicloud.com/api/messages",  // 华为云API网关地址
        "your_huawei_api_key_123456",                  // 您的华为云API密钥
        "smart_home_huawei_001",                       // 设备ID
        "华为云智能家居系统",                          // 项目名称
        15                                             // 超时时间（秒）
    );
    
    // 创建智能家居界面
    create_smart_home_ui();
    
    // 延迟1秒后恢复设备状态，让界面先完全加载
    lv_timer_t *restore_timer = lv_timer_create(restore_state_timer_cb, 1000, NULL);
    lv_timer_set_repeat_count(restore_timer, 1);
}